/**
 * 用户相关服务
 */

const util = require('../utils/util.js');
const api = require('../config/api.js');


/**
 * 调用微信登录
 */
function loginByWeixin(userInfo) {

  let code = null;
  let myUserInfo = userInfo;
  return new Promise(function(resolve, reject) {
    return util.login().then((res) => {
      code = res.code;
      // return util.getUserInfo();
    }).then((userInfo) => {
    //登录远程服务器
      util.request(api.AuthLoginByWeixin, {
        code: code,
        ...myUserInfo
      }, 'POST',true).then(res => {
        if(res.code==200){
          resolve(res);
        }else{
          reject(err);
        }
        // if (res.code == 400) {
        //   console.log("新用户");
        //   //注册用户
        //   let userInfoData = myUserInfo;
        //   var user = new User(res.result.openid, userInfoData.avatarUrl,userInfoData.nickName,userInfoData.gender);
        //   SaveByWeixin(user).then(res=>{
        //     resolve(res);
        //   })
          
        // } else if (res.code == 200) {
        //   console.log("已经存在用户");
        //   resolve(res);
        // }

      }).catch((err) => {
        reject(err);
      });
    }).catch((err) => {
      reject(err);
    })
  });
}

/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function(resolve, reject) {
    if (wx.getStorageSync('userInfo') && wx.getStorageSync('token')) {

      util.checkSession().then(() => {
        resolve(true);
      }).catch(() => {
        reject(false);
      });

    } else {
      reject(false);
    }
  });
}

/**
 * 返回注册后的用户
 */
function SaveByWeixin(user) {
  return new Promise((resolve,reject) => {
    wx.request({
      url: api.AuthSaveByWeixin, 
      data: user,
      method:"POST",
      header: {
        'content-type': "application/json" 
      },
      success(res) {
        if(res.data.code == 200){
          resolve(res.data);
        }else{
          reject("用户信息保存失败");
        }
      }
    })
  })
}

class User{
  openid;
  avatarUrl;
  nickName;
  gender;
  constructor(openid, avatarUrl, nickName,gender){
    this.openid = openid;
    this.avatarUrl = avatarUrl;
    this.nickName = nickName;
    this.gender = gender;
  }
}



module.exports = {
  loginByWeixin,
  checkLogin,
};